import os
import sys
from pathlib import Path

from dynaconf import FlaskDynaconf
from flask import Flask
from flask_cors import CORS

from project_name.errors import init_error_handlers
from project_name.ext.commands import create_db
from project_name.ext.database import init_app as db_init_app

Admin_DIR = Path("project_name", "static", "Admin")
User_DIR = Path("project_name", "static", "User")
source_file = 'templates/source.xlsx'
dev_resource_url = "http://localhost:5000"
prd_resource_url = "http://43.138.229.42:6089"


def create_app(**config):
    app = Flask(__name__)
    FlaskDynaconf(app)  # config managed by Dynaconf
    app.config.load_extensions(
        "EXTENSIONS"
    )  # Load extensions from settings.toml
    app.config.update(config)  # Override with passed config
    CORS(app, resources={r"/api/v1/*": {
        "origins": "*",
        "methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
        "allow_headers": ["Content-Type", "Authorization"]}
    })
    with app.app_context():
        create_db()

    # 创建管理员和用户资源保存文件夹
    # 获取应用根目录路径（更可靠的方式）
    base_dir = Path(app.root_path).parent

    # 创建目录
    admin_dir = base_dir / Admin_DIR
    user_dir = base_dir / User_DIR
    Path(admin_dir).mkdir(parents=True, exist_ok=True)
    Path(user_dir).mkdir(parents=True, exist_ok=True)

    # 全局变量
    # app.config['manual_env'] = "dev"
    app.config['user_dir'] = user_dir
    app.config['admin_dir'] = admin_dir

    if sys.platform.startswith('linux'):
        # Linux 特定代码
        app.config['resource_url'] = prd_resource_url
    elif sys.platform.startswith('win'):
        # Windows 特定代码
        app.config['resource_url'] = dev_resource_url

    print(f"current resource url : {app.config['resource_url']}")
    init_error_handlers(app)
    return app


def create_app_wsgi():
    # workaround for Flask issue
    # that doesn't allow **config
    # to be passed to create_app
    app = create_app()
    init_error_handlers(app)
    env = app.config.current_env
    print(f"当前环境: {env}")
    return app
